package com.example.contextcube.util;

import android.content.Context;
import android.content.SharedPreferences;
import androidx.preference.PreferenceManager;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 管理最近查询记录
 */
public class RecentQueriesManager {
    private static final String KEY_RECENT_QUERIES = "recent_queries";
    private static final int MAX_RECENT_QUERIES = 10;

    private final SharedPreferences preferences;

    public RecentQueriesManager(Context context) {
        this.preferences = PreferenceManager.getDefaultSharedPreferences(context);
    }

    /**
     * 添加一个查询记录
     * @param query 查询的单词
     */
    public void addQuery(String query) {
        if (query == null || query.trim().isEmpty()) {
            return;
        }

        List<String> queries = getRecentQueries();
        
        // 删除已存在的相同查询（如果有）
        queries.remove(query);
        
        // 添加到列表顶部
        queries.add(0, query);
        
        // 限制列表大小
        while (queries.size() > MAX_RECENT_QUERIES) {
            queries.remove(queries.size() - 1);
        }
        
        // 保存更新后的列表
        saveQueries(queries);
    }

    /**
     * 获取最近的查询记录
     * @return 查询记录列表
     */
    public List<String> getRecentQueries() {
        String jsonString = preferences.getString(KEY_RECENT_QUERIES, "[]");
        List<String> queries = new ArrayList<>();
        
        try {
            JSONArray jsonArray = new JSONArray(jsonString);
            for (int i = 0; i < jsonArray.length(); i++) {
                queries.add(jsonArray.getString(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        
        return queries;
    }

    /**
     * 清除所有最近查询记录
     */
    public void clearRecentQueries() {
        saveQueries(Collections.emptyList());
    }

    /**
     * 删除指定的查询记录
     * @param query 要删除的查询
     */
    public void removeQuery(String query) {
        List<String> queries = getRecentQueries();
        queries.remove(query);
        saveQueries(queries);
    }

    /**
     * 将查询列表保存到SharedPreferences
     * @param queries 查询列表
     */
    private void saveQueries(List<String> queries) {
        JSONArray jsonArray = new JSONArray();
        for (String query : queries) {
            jsonArray.put(query);
        }
        
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(KEY_RECENT_QUERIES, jsonArray.toString());
        editor.apply();
    }
} 